<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @abstract 订单轨迹API
 * @author zxj
 */
class OrderTrack extends CI_Controller
{
    private $t_order = 'maintain_order';
    function __construct()
    {
        parent::__construct();
    }


    /**
     * 获取订单轨迹
     * @param string $oid
     * @return bool
     */
    function get_order_track($oid = '')
    {
        $oid = $oid?$oid:gp('oid');
        if (!$oid){
           show_error('The order ID can not be empty');
        }
        $oid = trim($oid);
        $orderFirst = $this->common_model->selectFirst($this->t_order,array('maintain_id'=>$oid));
        $sql = 'select t.*,s.* from maintain_track t left join maintain_status s on t.target_status=s.status_id where t.maintain_id=\''.$oid.'\' ';
        $orderTrackList = $this->common_model->getQuery($sql,'result_array');
        json_output(array('orderFirst'=>$orderFirst,'orderTrackList'=>$orderTrackList),'succeed!',true);
    }


    /**
     * 获取订单追踪号
     * @param string $oid
     */
    function get_order_info($oid = ''){
        $oid = $oid?$oid:gp('oid');
        if (!$oid){
            show_error('The order ID can not be empty');
        }
        $oid = trim($oid);
        $orderFirst = $this->common_model->selectFirst($this->t_order,array('maintain_id'=>$oid));
        json_output($orderFirst,'succeed!',true);
    }


    function setTracking($oid = ''){
        $oid = $oid?$oid:gp('oid');
        if (!$oid){
            show_error('The order ID can not be empty');
        }
        $oid = trim($oid);
        $orderFirst = $this->common_model->selectFirst($this->t_order,array('maintain_id'=>$oid));
        if(!$orderFirst || !$orderFirst['track_num']){
            show_error('track number not Null');
        }
        $url = "http://tomrepair.es/~tomrepair/api/setTracking";
        $data_to_post = array();
        $data_to_post['user'] = 'api@tomrepair.es';
        $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
        $data_to_post['oid'] = $oid;
        $data_to_post['tracking'] = $orderFirst['track_num'];
        $headers[] = 'Authorization: DMCOHh3Y6Zf562MaDU3YzMyRjp3RFP9987trzdLZRZzcjFt';
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data_to_post));
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            $result = curl_error($curl);
            gsh_output($data_to_post);
        }else{
            $result = json_decode($result,true);

        }
        curl_close($curl);
        return $result;
    }


}
